package com.leetcode.algorithm.y22.m07.w2;

import com.leetcode.algorithm.common.ListNode;

/**
 * 61. 旋转链表
 * 
 * https://leetcode.cn/problems/rotate-list/
 * 
 * @author jie.deng
 *
 */
class Question0061Solution01 {
	
	public ListNode rotateRight(ListNode head, int k) {
		if (head == null || head.next == null || k == 0) {
			return head;
		}
		ListNode tail = null;
		int cnt = 1;
		tail = head;
		while (tail.next != null) {
			cnt++;
			tail = tail.next;
		}
		k = k % cnt;
		k = (cnt - k) % cnt;
		if (k == 0) {
			return head;
		}
		ListNode cur = head;
		while (k > 1) {
			cur = cur.next;
			k--;
		}
		ListNode newHead = cur.next;
		cur.next = null;
		tail.next = head;
		return newHead;
	}
    
}